package com.example.jenkinsplugins.json;

import java.util.*;

/**
 * @author meihaohui
 * @version 1.0
 * @descrption desc
 * @date 2023/11/28 8:56
 */
public class TreeNode {
    private String value;
    private List<TreeNode> children;
    private int depth; // 新增深度属性
    
    @Override
    public int hashCode() {
        return Objects.hash(value);
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        TreeNode treeNode = (TreeNode) obj;
        return Objects.equals(value, treeNode.value);
    }
    
    public TreeNode(String value) {
        this.value = value;
        this.children = new ArrayList<>();
        this.depth = 0; // 初始深度为 0
    }
    
    public TreeNode(String value,int depth) {
        this.value = value;
        this.children = new ArrayList<>();
        this.depth = depth;
    }
    
    public void setValue(String value) {
        this.value = value;
    }
    
    public void setChildren(List<TreeNode> children) {
        this.children = children;
    }
    
    public int getDepth() {
        return depth;
    }
    
    public void setDepth(int depth) {
        this.depth = depth;
    }
    
    public String getValue() {
        return value;
    }
    
    public List<TreeNode> getChildren() {
        return children;
    }
    
    public void addChild(TreeNode child) {
        children.add(child);
    }
    
    public static void main(String[] args) {
        // 创建Set<Map>并添加元素
        Set<Map<String, Object>> treeNodeSet = new HashSet<>();
        
        TreeNode node3 = new TreeNode("John", 1);
        TreeNode node1 = new TreeNode("John", 2);
        TreeNode node2 = new TreeNode("Jane", 3);
        
        addTreeNodeToSet(treeNodeSet, node1);
        addTreeNodeToSet(treeNodeSet, node2);
        addTreeNodeToSet(treeNodeSet, node3);
        
        // 输出去重后的结果
        for (Map<String, Object> map : treeNodeSet) {
            System.out.println("Value: " + map.get("value") + ", Depth: " + map.get("depth"));
        }
    }
    
    public static void addTreeNodeToSet(Set<Map<String, Object>> set, TreeNode node) {
        Map<String, Object> existingMap = null;
        
        for (Map<String, Object> map : set) {
            if (Objects.equals(map.get("value"), node.value)) {
                existingMap = map;
                break;
            }
        }
        
        if (existingMap != null) {
            existingMap.put("depth", Math.max((int) existingMap.get("depth"), node.depth));
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("value", node.value);
            map.put("depth", node.depth);
            set.add(map);
        }
    }
    
}
